package com.mall.untils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;

/**
 * Created by sa on 2015/5/28 15:46
 */
public class UploadImgOrRecorderUtil {

    static Logger logger = LoggerFactory.getLogger(UploadImgOrRecorderUtil.class);

    public static final int cache = 10 * 1024;

    public static String createImgFileByName(InputStream in, long fileLength, String fileName) {
        String endpoint = "http://ideal.oss-cn-beijing.aliyuncs.com/";

        try {
            putObject(Constants.BUCKETNAME, fileName, in, fileLength);

            return endpoint + fileName;
        } catch (Exception ex) {
            logger.error(ex.toString());
            return null;
        }

    }

    /**
     * 通过文件路径和文件名 在服务器端生成文件
     *
     * @param fileName
     */
    public static String saveFilesByName(String url, String fileName) throws Exception {
        // 以杭州为例
        String endpoint = "http://ideal.oss-cn-beijing.aliyuncs.com/";
        // 生成一个httpclient对象
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = client.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        long fileLength = entity.getContentLength();

        putObject(Constants.BUCKETNAME, fileName, in, fileLength);

        client.getConnectionManager().shutdown();
        return endpoint + fileName;
    }

    /**
     * 通过文件路径和文件名 在服务器端生成文件
     *
     * @param fileName
     */
    public static String saveVoiceByURL(String url, String fileName, String fileDir) throws Exception {
        // 以杭州为例
        String endpoint = "http://ideal.oss-cn-beijing.aliyuncs.com/";
        // 生成一个httpclient对象
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = client.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();

        // 保存文件
        File file = new File(fileDir + fileName + ".amr");
        file.getParentFile().mkdirs();
        FileOutputStream fileout = new FileOutputStream(file);
        /**
         * 根据实际运行效果 设置缓冲区大小
         */
        byte[] buffer = new byte[cache];
        int ch = 0;
        while ((ch = in.read(buffer)) != -1) {
            fileout.write(buffer, 0, ch);
        }
        in.close();
        fileout.flush();
        fileout.close();

        int result = ChangeAudioFormat.ToMp3(fileDir + fileName + ".amr", fileDir + fileName + ".mp3");

        if (result == 1) {
            putObject(Constants.BUCKETNAME, fileName + ".mp3", fileDir + fileName + ".mp3");
        }

        client.getConnectionManager().shutdown();
        return endpoint + fileName + ".mp3";
    }


    public static String putObject(String bucketName, String key, InputStream content, long fileLength) throws FileNotFoundException {
        // 初始化OSSClient
        String accessKey = "otP8H6jeFp5WnOEp";
        String accessSecret = "uvolZ0ddu94Ze8EbCiRbdhP6yS11PV";
        // 以杭州为例
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";

        OSSClient client = new OSSClient(endpoint, accessKey, accessSecret);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();
        // 必须设置ContentLength
        meta.setContentLength(fileLength);
        // 上传Object.
        PutObjectResult result = client.putObject(bucketName, key, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
        return result.getETag();
    }

    public static void putObject(String bucketName, String key, String filePath) throws FileNotFoundException {
        // 初始化OSSClient
        String accessKey = "otP8H6jeFp5WnOEp";
        String accessSecret = "uvolZ0ddu94Ze8EbCiRbdhP6yS11PV";
        // 以杭州为例
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";

        OSSClient client = new OSSClient(endpoint, accessKey, accessSecret);

        // 获取指定文件的输入流
        File file = new File(filePath);
        InputStream content = new FileInputStream(file);
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();
        // 必须设置ContentLength
        meta.setContentLength(file.length());

        // 上传Object.
        PutObjectResult result = client.putObject(bucketName, key, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }
}
